define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'lightboxme',
  'dateformatter',
  'multiselect',
  'multiselectfilter',
  'ckeditor',
  'models/appointment/DoctorModel',
  'models/history/PatientHistoryModel',
  'text!templates/appointments/doctorAppointmentTemplate.html',
  'text!templates/history/ropatientHistoryTemplate.html'
], function($,JQueryUI, _, Backbone,LightBoxMe,Dateformatter,Multiselect,Multiselectfilter,ck, DoctorModel,PatientHistoryModel, appointmentTemplate,ropatientHistoryTemplate){

  var DoctorView = Backbone.View.extend({
    el: $(".mainpanel"),
    model: new DoctorModel(),
    initialize: function(){
    	//_.bindAll(this, "changed");
 
    },
    events: { "change #profiles" :"addProfile",
    		"change #examinations" :"addType",
    		'click #savePrescription' : 'savePrescription',
    		'click .videoimg' : 'startVideo',
    		'click .preports':'showPatientReport',
    		'click .phistory':'showPatientHistory'} ,
    render: function(appointment){
    	this.appointment = appointment;
        var PatientHistoryList = Backbone.Collection.extend({
            model: Backbone.Model.extend({url:'/getHistoryResults/'+this.appointment.get("patient").id}),
            url:'/getHistoryResults/'+this.appointment.get("patient").id
          });
        
        this.patientHistoryList = new PatientHistoryList();
    	
    	console.log(appointment);
    	this.model.set("appointmentId", appointment.get("id"));
    	var self=this;
      	 $.ajax({
 	        type: "GET",
 	        url: "/getExaminations",
 	        success: function(response){
 	        	self.profiles=response.profiles;
 	        	self.examinations= response.examinations;
 	           var data = {
 	                  appointment: appointment,
 	                  _: _ ,
 	                  examinations:response.examinations,
 	                  profiles: response.profiles,
 	                 subtype: response.subtype,
 	                 distinctprofiles: response.dprofiles,
 	                 labs: response.labs
 	                };
 	  	      var compiledTemplate = _.template( appointmentTemplate, data );
 	  	      self.$el.html(compiledTemplate);

 	  	      $("#profiles").multiselect({
 	  	    	noneSelectedText: "Profiles"
 	  	    	}).multiselectfilter();
 	  	      $("#examinations").multiselect({
 	  	    	noneSelectedText: "Examinations"
	  	    	}).multiselectfilter();
 	  	   $("#labs").multiselect({
 	  		   	multiple: false,
 	  		   	header: "Labs",
	  		   	selectedList: 1,
	  	    	noneSelectedText: "Labs"
	  	    	}).multiselectfilter();
 	  	   
 	  	      $(".ui-multiselect").addClass("docselect");
  			if(CKEDITOR.instances['editor1'])
  			   delete CKEDITOR.instances['editor1'];
  			CKEDITOR.replace('editor1');

 	        }
 	    });

    },
    savePrescription: function(){
    	var tests=[];
    	$('.tableexam :checked').each(function(){
    		tests.push($(this).val());
    	});
        this.model.set("tests",tests);
        this.model.set("appointmentDoctorComment",CKEDITOR.instances['editor1'].getData());
        this.model.set("lab",$("#labs").val());
        console.log(this.model);
       	this.model.save(null, {
		    success: function (model, response) {
	      		 $.msgBox({
				    title:"Appment",
				    content:"Successfully Saved!",
				    type:"info"
				});

		    },
		    error: function (model, response) {
		        console.log("error");
		    }
		});


    },
    addProfile: function(evt){
    	this.addExaminations("profile", $("#profiles").val())
    },
    addType: function(evt){
    	this.addExaminations("type", $("#examinations").val())
    },
    startVideo: function(){
    	if(new Date(this.appointment.get("dateOfAppointment")).compare(new Date()) >0  ){
    		var me = this;
    		$.msgBox({
			    title:"Appment",
			    content:"This video conference is not scheduled for today. Do you really want to start it now?",
			    type: "confirm",
			    buttons: [{ value: "Yes" }, { value: "No" }],
			    success: function (result) {
			        if (result == "Yes") {
			        	me.goTo("videosession");
			        }
			    }
    		});
    	}else{
    		this.goTo("videosession");
    	}
    },
    addExaminations: function(type,selected){
    	if(type =="profile"){
    		var profiles=this.profiles;
    		var html="";
    		var count=0;
    		for(var i in profiles){
    			if(profiles[i].profileName == selected[selected.length-1]){
        			if(count < 3){
        				html = html == ""?"<tr>":html;
    					html=html+"<td><input type=\"checkbox\" name=\"checkexam\" checked value="+ profiles[i].examination.id +">"+profiles[i].examination.examinationName+"</td>";
    					count=count+1;
        			}else{
        				html=html+"<td><input type=\"checkbox\" name=\"checkexam\" checked value="+ profiles[i].examination.id +">"+profiles[i].examination.examinationName+"</td></tr>";
        				$('.tableexam tr:last').after(html); 
        				count=0;
        				html="";
        			}
    				
    			}
    		}
    		if(count > 0 && html) {
    			html=html+"</tr>"
				$('.tableexam tr:last').after(html); 
    			
    		}
    	}
    	if(type =="type"){
    		var exams=this.examinations;
    		var html="";
    		var count=0;
    		for(var i in exams){
    			if(exams[i].examinationSubtype == selected[selected.length-1]){
        			if(count < 3){
        				html = html == ""?"<tr>":html;
    					html=html+"<td><input type=\"checkbox\" name=\"checkexam\" value="+ exams[i].id +">"+exams[i].examinationName+"</td>";
    					count=count+1;
        			}else{
        				html=html+"<td><input type=\"checkbox\" name=\"checkexam\" value="+ exams[i].id +">"+exams[i].examinationName+"</td></tr>";
        				$('.tableexam tr:last').after(html); 
        				count=0;
        				html="";
        			}
    				
    			}
    		}
    		if(count > 0 && html) {
    			html=html+"</tr>"
				$('.tableexam tr:last').after(html); 
    			
    		}
    	}
    },
    showPatientReport: function(){
        var lOptions = {};
      //  var p = new PatientHistoryModel({id: appointment.get("patient").id});
        lOptions.success = function(){
            var data = {
          		  history: this.patientHistoryList,
          	        _: _ 
          	      };
            console.log(this.patientHistoryList);
   		   //   var compiledTemplate = _.template( ropatientHistoryTemplate, data );
   		    //  $(compiledTemplate).dialog({height:600,width:1000});
        };
       // this.patientHistoryList = new PatientHistoryList({id: this.appointment.get("patient").id});
        this.patientHistoryList.fetch(lOptions);
    },
    showPatientHistory: function(){
        var lOptions = {};
        var p = new PatientHistoryModel({id: 0});
        lOptions.success = function(){
            var data = {
          		  history: p,
          	        _: _ 
          	      };
   		      var compiledTemplate = _.template( ropatientHistoryTemplate, data );
   		      $(compiledTemplate).dialog({height:600,width:1000});
        };
        
        p.fetch(lOptions);

    }
  });

  return DoctorView;
});
